<script setup lang="ts">
import { Plus, Minus, } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus'
import {ref,inject} from 'vue'
import type { PicLink, PicLinkFunc, PicTitleDescStatusArr, statusType, updateStatusFunc, VueTypeCom } from '@/types'
import { EditorType, EditorTypeText } from '../../constants'

const props = defineProps<{
  id: string;
  isShow: boolean;
  name: string;
  editCom: VueTypeCom;
  configKey: EditorType;
  status: PicTitleDescStatusArr;
}>()
const updateStatus = inject<updateStatusFunc>('updateStatus',(configKey:string,payload:statusType)=>{})
const updatePicLink = inject<PicLinkFunc>('updatePicLink',(link:PicLink)=>{})

const optionArr = ref(props.status);
const addOptionHandle = ()=>{
  const lastOption  = optionArr.value[optionArr.value.length - 1]
  let num = 1;
  // 如果最后一个选项存在数字，则提取该数字并加1
  if (lastOption) {
    const match = lastOption.picTitle.match(/\d+/);
    if (match && !isNaN(+match[0])) {
      num = +match[0] + 1;
    }
  }

  const addStatus = '图片标题' + num;
  updateStatus(props.configKey,{
    picTitle: addStatus,
    picDesc: '说明（选填，限24字）',
    value: ''
  })

}

const removeOption = (index: number)=>{
  updateStatus(props.configKey,index)

}

const handlePreview = (index: number) => {
  ElMessageBox.confirm('是否确认删除已上传的图片？', '警告', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    console.log('点击了')
    updatePicLink({
        link: '',
        index
      })
    }).catch(() => {
      ElMessage.info('已取消删除');
  });
}
</script>

<template>
  <div class="options-editor">
    <div class="option-header flex align-items-center">
      <span>{{EditorTypeText[configKey]}}</span>
      <el-button  size="small" circle :icon="Plus" @click="addOptionHandle" />
    </div>
    <div class="option-item" v-for="(item, index) in optionArr" :key="index">
      <div class="flex align-items-center">
        <span class="title">选项{{index+1}}</span>
        <el-button
          type="danger"
          class="ml-10 delete"
          size="small"
          :icon="Minus"
          circle
          @click="removeOption(index)"
        />
      </div>
      <div class="flex title align-items-center">
        <span>{{item.value ? '已上传图片' : '未上传图片' }}</span>
        <el-button v-if="item.value" type="text" class="ml-5"  @click="handlePreview(index)">删除图片</el-button>
      </div>
      <div>
        <el-input v-model="item.picTitle" placeholder="标题" />
      </div>
      <div class="mt-10">
        <el-input type="textarea" :rows="3" maxlength="30" v-model="item.picDesc" placeholder="说明（选填，限30字）" />
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.option-item{
  margin: 10px 0;
  .title{
    font-size: var(--font-size-base);
    color: var(--font-color-light);
  }
  .delete{
    transform: scale(0.8);
  }
}

.option-header{
  span{
    margin-right: 5px;
  }
}
</style>
